<template>
    <myx-table
               :showTableSearch="false"
               :tableAttr="{
                   'default-expand-all': true,
                   border: true,
                   'header-cell-style': tableHeaderStyle
               }"
               :showSelection="true"
               :data="data"
               :column="column">
        <template #tableCell="{ scope }">
            <div v-if="scope.column?.key === 'action'">
                <el-button type="primary" @click="grantPermission(scope.row.roleid)">分配权限</el-button>
            </div>
            <div v-if="scope.column?.key === 'roleName'">
                <el-tag class="tag-2 twink" v-if="scope.row.roleid == 1" effect="dark">
                    {{ scope.row.roleName }}
                </el-tag>
                <el-tag v-else class="tag-1" effect="dark">
                    {{ scope.row.roleName }}
                </el-tag>
            </div>
            <div v-if="scope.column?.key === 'desc'">
                <el-tag effect="dark">
                    {{ scope.row.desc }}
                </el-tag>
            </div>
        </template>
    </myx-table>
    <myx-drawer :show="showDrawer"
                :openedFn="handleDrawerOpen"
                @drawer-close="drawerClose">
        <template #customButton>
            <el-button type="primary" class="twink" @click="savePermission">保存</el-button>
        </template>
        <template v-slot:nested>
            <el-tree
                     empty-text="正在加载..."
                     v-loading="treeLoading"
                     ref="treeRef"
                     :data="treeData"
                     show-checkbox
                     node-key="id"
                     default-expand-all
                     highlight-current
                     check-on-click-node
                     check-strictly
                     :props="treeProps" />
        </template>
    </myx-drawer>
</template>

<script setup>
import { onMounted } from "vue";
//引入将树形扁平化的方法
import flatTree from "@/utils/flatTree"
//引入扁平转树形的方法
import toTree from "@/utils/toTree"
//引入store
import usePermission from "@/store/permission"
import { ElMessage, ElMessageBox } from "element-plus";
import useUser from "@/store/users"

let userStore = useUser()
//声明表格数据

let data = ref([])

//声明表头样式

let tableHeaderStyle = { background: "#f6f7fa", height: "60px", color: "#000", textAlign: 'center' }

//定义列数据

let column = [
    {
        key: "roleid",
        label: '角色id',
        dataIndex: 'roleid',
        align: 'center'
    },
    {
        key: "roleName",
        label: '角色名称',
        dataIndex: 'roleName',
        align: 'center',
        tableCell: true
    },
    {
        key: "desc",
        label: '角色描述',
        dataIndex: 'desc',
        align: 'center',
        tableCell: true
    },
    {
        key: 'status',
        label: '角色状态',
        dataIndex: 'status',
        align: 'center'
    },
    {
        key: "action",
        label: '操作',
        tableCell: true,
        align: 'center'
    },
]

//获取角色的方法

let getRole = async () => {
    try {
        let res = await api.getRoleApi();
        data.value = res.data;
        console.log(data.value)
    } catch (e) {
        console.log(e.toString())
    }
}

//控制抽屉展开和隐藏的变量
let showDrawer = ref(false)

//点击分配权限的按钮
//存储当前点击的角色id
let currentRoleid = ref("")
let grantPermission = (roleid) => {
    //点击的时候对currentRoleid赋值
    currentRoleid.value = roleid;
    showDrawer.value = true
}

//抽屉收起的时候,要将showDrawer的值变成false
let drawerClose = param => {
    showDrawer.value = param;
}


//创建树形组件的引用

let treeRef = ref(null)

//树形tree

let treeProps = {
    label: 'desc'
}

//树形加载

let treeLoading = ref(false)

//树形组件的数据

let treeData = ref([])


//抽屉打开的时候触发的方法

let handleDrawerOpen = async () => {
    treeLoading.value = true
    // console.log('chouti opened')
    //获取所有的权限数据
    let allPermissions = (await api.getPermissionPathApi({ type: 1 })).permissionPaths
    // console.log(allPermissions)

    //获取当前角色的权限

    let currentRolePermission = (await api.getRolePermissionApi({ roleid: currentRoleid.value, type: '1' })).data

    let checkedKeys = currentRolePermission.map(item => item.id)

    treeRef.value.setCheckedKeys(checkedKeys)

    //将allPermissions树形数据转换成扁平数据

    let flatAllPermissions = flatTree(allPermissions);

    // console.log(flatAllPermissions)

    //从pinia将当前登入用户的权限获取

    let permissionStore = usePermission();

    //从store中获取登入用户的权限之后,将id映射成一个数组

    let loginUserPermissionIds = permissionStore.currentRolePermission.map(item => item.id)

    //只需要给数据添加一个disabled属性,那么对应选择框就会被禁用
    // console.log(currentRoleid.value)

    userStore.userInfo.roleid !== "1" && flatAllPermissions.forEach(item => {
        if (!loginUserPermissionIds.includes(item.id)) {
            item.disabled = true;
        }
    })

    //因为现在flatAllPermissions是个扁平数据,还需要将flatAllPermissions转换成树形数据才能够给tree使用

    let treeAllPermissions = toTree(flatAllPermissions)

    //给树形组件数据赋值
    treeData.value = treeAllPermissions;

    treeLoading.value = false;

}

//声明一个方法,保存授权收据,并且传递后台,进行角色授权操作

let savePermission = async () => {
    // console.log(treeRef.value.getCheckedKeys())
    //获取选中的权限数据
    ElMessageBox.confirm("是否确定要授权", "授权提示", {
        confirmButtonText: '授权',
        cancelButtonText: '取消',
        type: 'success'
    })
        .then(async () => {
            let checkedKeys = treeRef.value.getCheckedKeys();
            try {
                //参数
                let params = {
                    roleids: [currentRoleid.value],
                    permission_ids: checkedKeys
                }
                let res = await api.grantRoleApi(params);
                //提示
                ElMessage.success(res.msg)
                //关闭抽屉
                showDrawer.value = false;
            } catch (e) {
                console.log(e.toString())
            }
        })
        .catch(() => {
            ElMessage.warning('已取消授权')
        })
}

onMounted(() => {
    getRole()
})


</script>
<script>
export default {
    name: 'role',
    meta: {
        name: "角色管理",
        icon: "icon-jiaoseguanli"
    }
}
</script>

<style scoped>
.tag-1 {
    background-image: var(--theme-bg);
    padding: 1.3em;

}

@keyframes changeImg {
    from {
        left: -20%;
    }

    100% {
        left: 120%;
    }
}

.twink {
    /* width:100%;
    height:100%; */
    overflow: hidden;
    position: relative;
}

.twink::after {
    position: absolute;
    animation: changeImg 2s ease 0s infinite;
    top: 0;
    width: 40%;
    height: 100%;
    content: "";
    background: linear-gradient(to right, rgba(216, 204, 204, 0) 0, rgba(255, 255, 255, 0.905) 50%, rgba(255, 255, 255, 0) 100%);
    transform: skewX(-45deg);
    animation-iteration-count: infinite;
}

.tag-2 {
    background-image: var(--gold-bg);
    padding: 1.3em;
    color: #000;
    font-weight: bold;
    border-style: none;
}
</style>